#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Time     :2020/11/23
# @Author   :Changshu
# @File     :Exercise_482.py
# 482. 密钥格式化

def licenseKeyFormatting(S: str, K: int) -> str:
    """
    r=[]
    n=len(S)
    first=n%K
    i=0
    while i<first:
        if S[i]=='-':
            continue
        if S[i].isalpha():
            r.append(S[i].upper())
        else:
            r.append(S[i])
        i+=1
    """
    r=[]
    i=len(S)-1
    while i>=0:
        j=0
        while j<K and i>=0:
            if S[i] == '-':
                i-=1
                continue
            if S[i].isalpha():
                r.insert(0,S[i].upper())
            else:
                r.insert(0,S[i])
            j+=1
            i-=1
        if i!=-1:
            r.insert(0, '-')
    if len(r)>0 and r[0]=='-':
        del r[0]
    return ''.join(r)

if __name__ == '__main__':
    # S='5F3Z-2e-9-w'
    # S='2-5g-3-J'
    # S='------a-a-a-a--'
    S='---'
    K=3
    print(licenseKeyFormatting(S,K))


